package com.bw.live_streaming.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bw.common.utils.R;
import com.bw.live_streaming.config.GuliESConfig;
import com.bw.live_streaming.feign.DocterLevelFeign;
import com.bw.live_streaming.vo.InquiryVo;
import com.bw.live_streaming.vo.InquiryVos;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.common.utils.PageUtils;
import com.bw.common.utils.Query;

import com.bw.live_streaming.dao.InquiryDao;
import com.bw.live_streaming.entity.InquiryEntity;
import com.bw.live_streaming.service.InquiryService;


@Service("inquiryService")
public class InquiryServiceImpl extends ServiceImpl<InquiryDao, InquiryEntity> implements InquiryService {

    @SuppressWarnings({"all"})
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private DocterLevelFeign docterLevelFeign;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<InquiryEntity> page = this.page(
                new Query<InquiryEntity>().getPage(params),
                new QueryWrapper<InquiryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R lists(InquiryVo vo) {
        R ok = R.ok();
        List<InquiryEntity> inquiryEntityList = baseMapper.selectList(null);
        try {
            if (inquiryEntityList!=null){
                for (InquiryEntity entity : inquiryEntityList) {
                    //创建请求索引对象
                    IndexRequest indexRequest = new IndexRequest("inquiry");
                    //id和对象放入索引
                    indexRequest.id(entity.getInquiryId().toString());
                    String s = JSON.toJSONString(entity);
                    indexRequest.source(s, XContentType.JSON);
                    client.index(indexRequest, GuliESConfig.COMMON_OPTIONS);
                }
            }
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices("inquiry");
            SearchSourceBuilder builder = new SearchSourceBuilder();
            //String key=".keyword";
            if(vo.getInquiryLabel()!=null || vo.getMsg()!=null){
                BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
                //根据标签名进行精确查找
                if(vo.getInquiryLabel()!=null && !vo.getInquiryLabel().equals("")){
                    MatchQueryBuilder inquiryLabel1 = QueryBuilders.matchQuery("inquiryLabel", vo.getInquiryLabel());

                    //定义一个标准
                    float a= (float)4;
                    //最小的评分标准
                    builder.minScore(a);
                    boolQuery.must(inquiryLabel1);
                }
                // 根据发送的信息进行查找
                if (vo.getMsg()!=null && !vo.getMsg().equals("")){
                    MatchQueryBuilder inquiryLabel1 = QueryBuilders.matchQuery("inquiryLabel", vo.getMsg());
                   // 定义一个标准
                    float a= (float) 3.1;
                    //最小的评分标准
                    builder.minScore(a);
                    boolQuery.must(inquiryLabel1);
                }

                builder.query(boolQuery);
            }
//
            //排序
            builder.sort("inquiryNum", SortOrder.DESC);

            searchRequest.source(builder);
            SearchResponse response = client.search(searchRequest, GuliESConfig.COMMON_OPTIONS);
            System.out.println(response);
            //从es中拿取数据
            SearchHits hits = response.getHits();
            SearchHit[] hits1 = hits.getHits();
            ArrayList<InquiryEntity> arrayList = new ArrayList<>();
            //将所有数据循环遍历出来
            for (SearchHit hit : hits1) {
                InquiryEntity inquiryEntity = JSON.parseObject(hit.getSourceAsString(), new TypeReference<InquiryEntity>() {
                });
                //将每一条数据存放到集合中
                arrayList.add(inquiryEntity);
            }
            //判断是否有需要查询的值
            if(vo.getInquiryLabel().equals("") && vo.getMsg().equals("") ){
                return ok.put("lists",arrayList);
            }else{
                //定义一个字符串来拼接标签
                String lists="";
                for (InquiryEntity inquiryEntity : arrayList) {
                   lists+=inquiryEntity.getInquiryLabel()+",";
                   //点击一次，点击量+1
                   baseMapper.updNum(inquiryEntity.getInquiryId(),1);
                }
                String list = lists.substring(0,lists.length()-1);
                //使用feign调用
                List<InquiryVos> doclist = docterLevelFeign.doclist(list);
                return ok.put("list",doclist);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return ok;
    }

}